package com.green.common.util;

import java.nio.ByteBuffer;

import org.apache.commons.codec.binary.Base64;

/**
 * 令牌工具
 * 
 * @author fengwenjin
 * 
 */
public class TokenUtil {

	private static final int VALID_TIMEE = 1 * 24 * 60 * 60 * 1000;
	private static final String DEFAULT_UID = "interface_user_96060";

	/**
	 * 获取默认令牌
	 * 
	 * @return String
	 */
	public static String getDefaultToken() {
		return encode(DEFAULT_UID);
	}

	/**
	 * 验证默认令牌
	 * 
	 * @param token
	 * @return boolean
	 */
	public static boolean validDefaultToken(String token) {
		String uid = decode(token);
		if (uid != null && uid.equals(DEFAULT_UID)) {
			return true;
		}
		return false;
	}

	/**
	 * 编码
	 * 
	 * @param uid
	 * @return String
	 */
	public static String encode(String uid) {
		try {
			int size = uid.getBytes().length;
			if(size > 64){
				return null;
			}
			ByteBuffer buf = ByteBuffer.allocate(size + 16);
			buf.putInt(size);
			buf.putInt(uid.hashCode());
			buf.put(uid.getBytes());
			buf.putLong(System.currentTimeMillis() + VALID_TIMEE);
			return Base64.encodeBase64URLSafeString(buf.array());
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 解码
	 * 
	 * @param token
	 * @return String
	 */
	public static String decode(String token) {
		try {
			ByteBuffer buf = ByteBuffer.wrap(Base64.decodeBase64(token));
			int size = buf.getInt();
			if(size > 64){
				return null;
			}
			int hashCode = buf.getInt();
			byte[] data = new byte[size];
			buf.get(data);
			long time = buf.getLong();
			if (System.currentTimeMillis() > time) {
				return null;
			}
			String uid = new String(data);
			if (uid.hashCode() == hashCode) {
				return uid;
			}
			return null;
		} catch (Exception e) {
			return null;
		}
	}

}
